//
//  PhotoEditorViewController.swift
//  ChildStory
//
//  Created by linhan on 16/8/19.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit

protocol PhotoEditorViewControllerDelegate:NSObjectProtocol
{
    func photoEditorViewController(_ controller:SWPhotoEditorViewController, didFinishProcessImage processedImage:UIImage, additionInfo info:[String:Any]?)
    func photoEditorViewControllerDidCancel(_ controller: SWPhotoEditorViewController)
}

//其他照片编辑器其他处理页面
protocol SWImageProcessViewControllerDelegate:NSObjectProtocol
{
    func imageProcessViewController(controller:UIViewController, didFinishProcessImage processedImage:UIImage, additionInfo info:[String:Any]?)
}

class SWPhotoEditorViewController: SWBaseViewController,SWImageProcessViewControllerDelegate,SWEditorExpandToolbarDelegate
{
    weak var delegate:PhotoEditorViewControllerDelegate?
    var additionInfo:[String:Any]?
    
    private let BackgroundColor = UIColor(hex: 0x232222)
    private let MainToolViewHeight:CGFloat = 62
    private let TopToolViewHeight:CGFloat = 62
    
    private var _image:UIImage
    private var _change:Bool = false
    private var _canvasCenter:CGPoint = CGPoint.zero
    private var _canvas:SWMainCanvas = SWMainCanvas()
    
    private var _expandToolbar:SWEditorExpandToolbar?
    private var _topToolbar:UIView = UIView()
    private var _mainToolbar:UIView = UIView()
    
    init(origin:UIImage)
    {
        _image = origin
        trace("editor:", origin.size)
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit
    {
        trace("DEINIT SWPhotoEditorViewController")
    }
    
    //隐藏导航栏
    override var prefersNavigationBarHidden: Bool{
        return true
    }
    
    //隐藏状态栏
    override var prefersStatusBarHidden:Bool {
        return true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    
    private func setup()
    {
        view.backgroundColor = BackgroundColor
        
        _topToolbar.frame = CGRectMake(0, 0, view.width, TopToolViewHeight)
        _topToolbar.backgroundColor = BackgroundColor
        view.addSubview(_topToolbar)
        
        let closeBtn:UIButton = UIButton(type: .custom)
        closeBtn.setImage(UIImage(named: "editor_icon_cancel"), for: .normal)
        closeBtn.sizeToTouchEasy()
        closeBtn.center = CGPointMake(22, 22)
        closeBtn.addTarget(self, action: #selector(closeBtnTapped), for: .touchUpInside)
        _topToolbar.addSubview(closeBtn)
        
        let saveBtn:UIButton = UIButton(type: .custom)
        saveBtn.setImage(UIImage(named: "editor_icon_ok"), for: .normal)
        saveBtn.sizeToTouchEasy()
        saveBtn.center = CGPointMake(view.width - 22, 22)
        saveBtn.addTarget(self, action: #selector(saveBtnTapped), for: .touchUpInside)
        _topToolbar.addSubview(saveBtn)
        
        view.addSubview(_canvas)
        
        
        
        _mainToolbar.frame = CGRectMake(0, view.height - MainToolViewHeight, view.width, MainToolViewHeight)
        _mainToolbar.backgroundColor = BackgroundColor
        view.addSubview(_mainToolbar)
        
        let effectBtn:UIButton = UIButton(type:.custom)
        effectBtn.setImage(UIImage(named:"editor_menu_effect"), for: .normal)
        effectBtn.sizeToTouchEasy()
        effectBtn.center = CGPointMake(view.width * 0.25, _mainToolbar.height * 0.5)
        effectBtn.addTarget(self, action: #selector(effectBtnTapped), for: .touchUpInside)
        _mainToolbar.addSubview(effectBtn)
        
        let editBtn:UIButton = UIButton(type:.custom)
        editBtn.setImage(UIImage(named:"editor_menu_basicedit"), for: .normal)
        editBtn.sizeToTouchEasy()
        editBtn.center = CGPointMake(view.width * 0.5, _mainToolbar.height * 0.5)
        editBtn.addTarget(self, action: #selector(editBtnTapped), for: .touchUpInside)
        _mainToolbar.addSubview(editBtn)
        
        
        let paintBlurBtn:UIButton = UIButton(type:.custom)
        paintBlurBtn.setImage(UIImage(named:"editor_menu_blur"), for: .normal)
        paintBlurBtn.sizeToTouchEasy()
        paintBlurBtn.center = CGPointMake(view.width * 0.75, _mainToolbar.height * 0.5)
        paintBlurBtn.addTarget(self, action: #selector(paintBlurBtnTapped), for: .touchUpInside)
        _mainToolbar.addSubview(paintBlurBtn)
        
        setImage(_image)
    }
    
    func close()
    {
        dismiss(animated: true, completion: nil)
    }
    
    func imageProcessViewController(controller:UIViewController, didFinishProcessImage processedImage:UIImage, additionInfo info:[String:Any]?)
    {
        _change = true
        setImage(processedImage)
    }
    
    private func setImage(_ image:UIImage)
    {
        let retinaImage:UIImage? = image.retinaImage
        let imageSize = retinaImage?.size ?? CGSize.zero
        _image = image
        _canvas.image = retinaImage
        print("setImage:", image.size, image.scale)
        let containerWidth:CGFloat = view.width
        let containerHeight:CGFloat = view.height - TopToolViewHeight - MainToolViewHeight
        let scale:CGFloat = ViewUtil.getAdaptiveScale(imageSize.width, targetH: imageSize.height, containerW: containerWidth, containerH: containerHeight)
        let canvasWidth:CGFloat = imageSize.width * scale
        let canvasHeight:CGFloat = imageSize.height * scale
        let canvasX:CGFloat = (containerWidth - canvasWidth) * 0.5
        let canvasY:CGFloat = TopToolViewHeight + (containerHeight - canvasHeight) * 0.5
        _canvas.frame = CGRectMake(canvasX, canvasY, canvasWidth, canvasHeight)
        _canvasCenter = _canvas.center
    }
    
    private func showExpandToolbar(_ toolbar:SWEditorExpandToolbar)
    {
        //当弹出的工具栏高于主工具栏时，画布上移
        let toolBarOffset = toolbar.height - _mainToolbar.height
        let moveCanvas:Bool = toolBarOffset > 0
        toolbar.canvas = _canvas
        toolbar.image = _image
        toolbar.toolbarWillAppear(true)
        toolbar.y = view.height
        view.addSubview(toolbar)
        _expandToolbar = toolbar
        
        UIView.animate(withDuration:0.3, animations: {
            toolbar.y = self.view.height - toolbar.height
            self._mainToolbar.y = self.view.height
            self._topToolbar.y = -self._topToolbar.height
            if moveCanvas
            {
                self._canvas.center = CGPointMake(self._canvasCenter.x, self._canvasCenter.y - toolBarOffset)
            }
        },completion:{finish in
            toolbar.toolbarDidAppear(true)
        })
    }
    
    private func hideExpandToolbar()
    {
        if let toolbar = _expandToolbar
        {
            let moveCanvas:Bool = toolbar.height > _mainToolbar.height
            toolbar.toolbarWillDisappear(true)
            UIView.animate(withDuration: 0.3, animations: {
                toolbar.y = self.view.height
                self._topToolbar.y = 0
                if moveCanvas
                {
                    self._canvas.center = self._canvasCenter
                }
            },completion:{finish in
                toolbar.toolbarDidDisappear(true)
                toolbar.removeFromSuperview()
                self._expandToolbar = nil
            })
        }
        
        UIView.animate(withDuration: 0.3, animations: {
            self._mainToolbar.y = self.view.height - self._mainToolbar.height
        })
    }
    
    
    //取消
    func expandToolbarCancel()
    {
        hideExpandToolbar()
    }
    
    //确定
    func expandToolbarConfirmed(_ image:UIImage)
    {
        hideExpandToolbar()
        _change = true
        setImage(image)
    }
    
    @objc private func saveBtnTapped()
    {
        delegate?.photoEditorViewController(self, didFinishProcessImage: _image, additionInfo: additionInfo)
    }
    
    @objc private func closeBtnTapped()
    {
        if _change
        {
            Alert.show("", message: "是否放弃当前图片操作?", buttons: ["放弃", "保留"], closeHandler: {buttonIndex in
                if buttonIndex == 0{
                    self.delegate?.photoEditorViewControllerDidCancel(self)
                }
            })
        }
        else
        {
            delegate?.photoEditorViewControllerDidCancel(self)
        }
        
    }
    
    @objc private func paintBlurBtnTapped()
    {
//        let viewController = SWPaintBlurViewController()
//        viewController.image = _image
//        viewController.delegate = self
//        viewController.modalTransitionStyle = .crossDissolve
//        let navigationController = SWBaseNavigationController(rootViewController: viewController)
//        present(navigationController, animated: false, completion: nil)
        let toolbar = SWEditorPaintBlurToolbar(frame: CGRectMake(0, 0, view.width, 0))
        toolbar.backgroundColor = BackgroundColor
        toolbar.optimizationSize = CGSizeMake(view.width, view.height - toolbar.height).multiply(UIScreen.main.scale)
        toolbar.delegate = self
        showExpandToolbar(toolbar)
    }
    
    @objc private func effectBtnTapped()
    {
        let toolbar = SWEditorEffectToolbar(frame: CGRectMake(0, 0, view.width, 0))
        toolbar.backgroundColor = BackgroundColor
        toolbar.optimizationSize = CGSizeMake(view.width, view.height - toolbar.height).multiply(UIScreen.main.scale)
        toolbar.delegate = self
        showExpandToolbar(toolbar)
    }
    
    @objc private func editBtnTapped()
    {
        let toolbar = SWEditorBaseEditToolbar(frame: CGRectMake(0, 0, view.width, 0))
        toolbar.backgroundColor = BackgroundColor
        toolbar.delegate = self
        showExpandToolbar(toolbar)
    }
    
    
    
}
